package org.noworks.game;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Input;
import org.newdawn.slick.geom.Vector2f;
import org.newdawn.slick.state.StateBasedGame;
import org.noworks.game.engine.Component;

public class SideScrollerMovement extends Component {
	
	boolean direction;
	float speed;
	
	boolean jumping = false;
	boolean grounded;
	
	float grav = 0.5f;
	
	float maxSpeed;
	
	float accel = 1;
	
	float dx = 0;
	float dy = 0;
	
	public SideScrollerMovement(String id) {
		this.id = id;
	}
	
	public float getSpeed() {
		return speed;
	}
	
	public boolean getDirection() {
		return direction;
	}

	@Override
	public void update(GameContainer gc, StateBasedGame sbg, int delta) {
		
		Input in = gc.getInput();
		
		if (in.isKeyDown(Input.KEY_W)) {
			
		}
		if (in.isKeyDown(Input.KEY_A)) {
			dx = -0.25f*Main.scale*delta;
		} else if (in.isKeyDown(Input.KEY_D)) {
			dx = 0.25f*Main.scale*delta;
		}
		else
			dx = 0;
		if (in.isKeyDown(Input.KEY_S)) {
			
		}
		if (in.isKeyPressed(Input.KEY_SPACE)) {
			if (!jumping) {
				dy = 0.32f;
				jumping = true;
				grounded = false;
			}
		}
		
		// FIXME: Gravity bounces back and forth between two pixels
		
		Vector2f pos = owner.getPosition();
		if (Gameplay.collisionMap[(int) (pos.x/Gameplay.tileSize)][(int) ((pos.y + owner.getHeight() + 2)/Gameplay.tileSize)]) {
			if (!grounded)
				grounded = true;
			jumping = false;
			pos.y--;
		}
		else
			grounded = false;
		if (jumping)
			dy -= grav*delta/1000;
		if (!jumping && !grounded)
			dy = -0.25f;
		else if (grounded)
			dy = 0;
		if (dy < -0.25f)
			dy = -0.25f;
		pos.y -= dy;
		pos.x += dx;
		if (pos.x < 0)
			pos.x = 0;
		owner.setPosition(pos);
	}

}
